#include "base/channel.h"
#include "net/buffer.h"
#include "net/buffer_reader.h"
#include "net/connect.h"
#include "net/heartbeat.h"

#include <unistd.h>

#include "net/connectpool.h"
namespace net_tools::net{

Connectpool::Connectpool(net_tools::Eventloop* eventloop,int base_size)
  :connect_number(0),
   eventloop_(eventloop)
{
  Buffer::buffer_reader_ = new Buffer_reader();
  connect_free_vector_.reserve(base_size);
  for(int count = 0;count < base_size;++count){
    Connect *connect = new Connect(eventloop_);
    connect_free_vector_.push_back(connect);
  }
};
Connect* Connectpool::Get_Connect(net_tools::base::Channel* channel)
{
  if(connect_free_vector_.empty()) [[unlikely]] { //small chance don't have free channel
//  if(channel_free_vector.empty()){
    for(int count = 0;count < _C::EACH_NEW_CONNECT;++count){
      Connect *connect = new Connect(eventloop_);
      connect_free_vector_.push_back(connect);
    }
  }
  Connect *connect = *connect_free_vector_.rbegin();
  connect_free_vector_.pop_back();
  connect->Init_channel(channel);
  ++connect_number;
  return connect;
};
void Connectpool::Free_Connect(Connect* old_Connect)
{
  connect_free_vector_.push_back(old_Connect);
  --connect_number;
};
void Connectpool::Set_heartbeat(connect_func heartbeat_lose_func){
  heartbeat_lose_func_ = std::move(heartbeat_lose_func);
  heartbeat_ = new Heartbeat(eventloop_,heartbeat_lose_func_);
};
void Connectpool::Start_heartbeat(){
  heartbeat_->Start();
};
void Connectpool::Stop_heartbeat(){
  heartbeat_->Stop();
};
void Connectpool::Add_heartbeat(Connect* connect){
  heartbeat_->Add_heartbeat(connect);
};
void Connectpool::Del_heartbeat(Connect* connect){
  heartbeat_->Del_heartbeat(connect);
};

} // namespace net_tools::base